//
//  CZPhotoSelectedController.swift
//  图片浏览
//
//  Created by itcast on 16/5/24.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

import HMImagePicker

private let reuseIdentifier = "Cell"

class CZPhotoSelectorController: UICollectionViewController {
    
    // 用户选择的图片数组
    var photos = [UIImage]()
    
    /// 选中资源素材数组，用于定位已经选择的照片
    var selectedAssets: [PHAsset]? = [PHAsset]()
//    @property (nonatomic) NSArray *selectedAssets;
    
    private let MaxImageCount = 6
    
    private let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.backgroundColor = UIColor.whiteColor()

        self.collectionView!.registerClass(CZPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        layout.itemSize = CGSize(width: 80, height: 80)
        self.collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

}

// MARK: - 数据源方法
extension CZPhotoSelectorController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 图片没有到达最大张数时,显示图片数量+1个cell
        // 图片到达最大张数时,显示最大张数个cell
        return photos.count < MaxImageCount ? photos.count + 1 : MaxImageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZPhotoSelectorCell
        
        cell.backgroundColor = UIColor.brownColor()
        cell.delegate = self
        
        // 给cell设置图片
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        } else {
            // 显示加号按钮
            cell.setupAddButton()
        }
        
        return cell
    }
}

// MARK: - 遵守cell的协议
extension CZPhotoSelectorController: CZPhotoSelectorCellDelegate {
    /// 删除按钮被点击
    func photoSelectroCellDidClickDeleteButton(cell: CZPhotoSelectorCell) {
        // 获取cell对应的indexPath
        let indexPath = collectionView!.indexPathForCell(cell)!
        photos.removeAtIndex(indexPath.item)
        
        collectionView?.reloadData()
    }
    
    /// 加号按钮被点击
    func photoSelectorCellDidClickAddButton(cell: CZPhotoSelectorCell) {
        // 弹出系统相册
//        let picker = UIImagePickerController()
//        
//        picker.delegate = self
        
//        HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
//        
//        // 设置图像选择代理
//        picker.pickerDelegate = self;
//        // 设置目标图片尺寸
//        picker.targetSize = CGSizeMake(600, 600);
//        // 设置最大选择照片数量
//        picker.maxPickerCount = 9;
        
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        // 设置图像选择代理
        picker.pickerDelegate = self
        // 设置目标图片尺寸
        picker.targetSize = CGSize(width: 100, height: 100)
        // 设置最大选择照片数量
        picker.maxPickerCount = 9
        
        presentViewController(picker, animated: true, completion: nil)
    }
}

// MARK: - 遵守选择多张图片的代理
extension CZPhotoSelectorController: HMImagePickerControllerDelegate {
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        // 记录图像，方便在 CollectionView 显示
        self.photos = images;
        
        // 记录选中资源集合，方便再次选择照片定位
        self.selectedAssets = selectedAssets
        
        self.collectionView?.reloadData()
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - 遵守UIImagePickerController协议
extension CZPhotoSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 用户选择了图片就会调用这个代理方法
    // 当实现这个代理方法就需要自己手动关闭弹出来的控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print("image: \(image)")
        // 把图片截小
        
        let newImage = image.scaleImage(300)
         print("newImage: \(newImage)")
        photos.append(newImage)
        
        collectionView?.reloadData()
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}